<?php

namespace app\common\model;

use think\Model;
use think\Db;
class Notice extends Model
{
    protected $resultSetType = 'collection';
    public static function get_notice_list($page,$user_id,$add_time)
    {
        $where = "add_time > '{$add_time}'";
        $field = "id,title,content,add_time";
        $order = "add_time DESC";
        $count = self::where($where)->count();
        $limit = 20;
        $start = ($page - 1) * $limit;
        $total = ceil($count / $limit);
        $list = self::where($where)->field($field)->order($order)->limit($start, $limit)->select()->toArray();
        foreach ($list as &$value){
            $read_info = Db::name("notice_read")->where(["user_id"=>$user_id,"notice_id"=>$value["id"]])->find();
            if($value["content"]){
                $value["content"] = StringToText($value["content"],200);
            }else{
                $value["content"] = "";
            }
            if($read_info){
                $value['is_read'] = 1; //已读
            }else{
                $value['is_read'] = 2; //未读
            }
        }
        $data = [
            'total'=>$total,
            'list'=>$list
        ];
        return $data;
    }

    public static function get_notice_info($id,$user_id)
    {
        $where = "id = {$id}";
        $info = self::where($where)->field("*")->find();
        if($info && !empty($info["content"])){
            $info["content"]=get_image_url($info["content"],protocol_name() . '://' . $_SERVER['SERVER_NAME']);
        }
        $current_year = date('Y',time());
        $year = date('Y',strtotime($info['add_time']));
        if($current_year != $year){
            $info["release_time"] = date('Y年m月d日',strtotime($info['add_time']));
        }else{
            $info["release_time"] = date('m月d日',strtotime($info['add_time']));
        }
        self::where($where)->setInc('view',1);
        $read_info = Db::name("notice_read")->where(["user_id"=>$user_id,"notice_id"=>$id])->find();
        if(!$read_info){
            $read_data = [];
            $read_data["user_id"] = $user_id;
            $read_data["notice_id"] = $id;
            $read_data["add_time"] = time();
            Db::name("notice_read")->insert($read_data);
        }
        return $info;
    }

    public function getAddTimeAttr($value)
    {
        if($value){
            return date("Y-m-d H:i:s",$value);
        }else{
            return "";
        }
    }
}
